﻿
using Microsoft.AspNetCore.Mvc;
using SHZY.Business.Entitys.Entity;
using SHZY.Business.Interfaces;
using SHZY.Common.Core.Manager;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SqlSugar;
using SHZY.JsonSerialization;
using Spire.Presentation;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;
using SHZY.BaseData.Entitys.Dto.QmsBaseCustomer;
using System.Text.Json.Nodes;
using Newtonsoft.Json.Linq;
using SHZY.Common.Security;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using Mapster;
using SHZY.Common.Enum;
using SHZY.FriendlyException;
using SHZY.Business.Entitys;
using NPOI.SS.Formula.Functions;
using SHZY.BaseData.Entitys;
using Yitter.IdGenerator;
using System.Reactive;
using Org.BouncyCastle.Asn1.Tsp;
using SHZY.BaseData.Entitys.Entity.Samplingplan;

namespace SHZY.Business
{

    /// <summary>
    /// 业务实现：检验批项目.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "IpqcInspectionitem", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiIpqcinspectionitemService : IQmsBusiIpqcinspectionitemService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiIpqcinspectionitemEntity> _repository;


        private readonly ITenant _db;

        /// <summary>
        /// 数据字典服务.
        /// </summary>
        private readonly IDictionaryDataService _dictionaryDataService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiIpqcinspectionitemService"/>类型的新实例.
        /// </summary>
        public QmsBusiIpqcinspectionitemService(
            ISqlSugarRepository<QmsBusiIpqcinspectionitemEntity> qmsBusiIpqcinspectionitemRepository,
            ISqlSugarClient context,
            IUserManager userManager,
            IDictionaryDataService dictionaryDataService)
        {
            _repository = qmsBusiIpqcinspectionitemRepository;
            _userManager = userManager;
            _db = context.AsTenant();
            _dictionaryDataService = dictionaryDataService;
        }

        /// <summary>
        /// 获取检验批项目列表.
        /// </summary>
        /// <param name="code">检验批号.</param>
        /// <returns></returns>
        [HttpGet("{code}")]
        public async Task<dynamic> GetList(string code)
        {
            // 查询检验项目
            var ipqcInspectionitemList = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemEntity>()
                .Where(x => x.Code == code && x.DeleteMark == null && x.EnabledMark == 1)
                .OrderBy(" F_SampleId asc,F_CreatorTime asc").ToListAsync();
                //.OrderBy(x => x.CreatorTime, OrderByType.Asc).ToListAsync();

            // 查询最大的抽样数量，以此确认动态列数量
            var samplingQty = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemEntity>().Where(x => x.Code == code && x.DeleteMark == null && x.EnabledMark == 1).MaxAsync(x => x.SamplingQty);
            samplingQty = samplingQty ?? 0;

            // 查询检验项目检验结果数据
            var ipqcInspectionitemdataList = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemdataEntity>()
            .Where(x => x.Code == code && x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.CreatorTime, OrderByType.Asc).ToListAsync();

            // 获取动态列标题
            JArray customColumnArray = new JArray();
            for (int i = 1; i <= samplingQty; i++)
            {
                JObject jObject = new JObject();
                jObject.Add("index", i);
                var ipqcInspectionitemdata = ipqcInspectionitemdataList.Find(x => x.Number == i);
                if (ipqcInspectionitemdata != null)
                {
                    jObject.Add("columnName", ipqcInspectionitemdata.Serial.Equals("")? i.ToString(): ipqcInspectionitemdata.Serial);
                }
                else
                {
                    jObject.Add("columnName", i.ToString());
                }
                customColumnArray.Add(jObject);
            }

            // 拼接检验项目与检验结果数据
            JArray jArray = new JArray();
            string sampleId = "";
            foreach (var item in ipqcInspectionitemList)
            {
                string itemJson = item.ToJsonString();
                var jObject = JObject.Parse(itemJson);
                jObject["FileInfo"] = JArray.Parse(jObject["FileInfo"].ToString());
                if (sampleId.Equals(item.SampleId))
                {
                    jObject["SamplingTypeDes"] = "";
                }
                else
                {
                    sampleId = item.SampleId;
                }

                // 查询检验项目缺陷记录
                var ipqcInspectionitemdefectList = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemdefectEntity>()
                .Where(x => x.InspectionItem == item.Id && x.DeleteMark == null && x.EnabledMark == 1)
                .OrderBy(x => x.CreatorTime, OrderByType.Desc).ToListAsync();
                // 得到缺陷总数和缺陷状态
                int total = ipqcInspectionitemdefectList.Count;
                jObject.Add("defectQty", total);
                jObject.Add("defectStatus", total > 0 ? "Y" : "N");


                for (int i = 1; i <= item.SamplingQty; i++)
                {
                    var ipqcInspectionitemdata = ipqcInspectionitemdataList.Find(x => x.InspectionItem == item.Id && x.Number == i);
                    int defectQty = ipqcInspectionitemdefectList.FindAll(x => x.Number == i).Count;
                    var columnValue = new JObject();
                    if (ipqcInspectionitemdata != null)
                    {
                        columnValue.Add("value", ipqcInspectionitemdata.Value);
                        columnValue.Add("status", ipqcInspectionitemdata.Status);
                        columnValue.Add("defectQty", defectQty);
                        jObject.Add("column" + i, columnValue);
                    }
                    else
                    {
                        columnValue.Add("value", "");
                        columnValue.Add("status", defectQty > 0 ? "NG" : "");
                        columnValue.Add("defectQty", defectQty);
                        jObject.Add("column" + i, columnValue);
                    }
                }
                jArray.Add(jObject);
            }
            return new { list = jArray, customColumnList = customColumnArray };
        }

        /// <summary>
        /// 修改抽样数量.
        /// </summary>
        /// <param name="data">参数.</param>
        /// <returns></returns>
        [HttpPut("SamplingQty")]
        public async Task UpdateSamplingQty([FromBody] JObject _data)
        {
            string code = _data["code"].ToString();
            string sampleId = _data["sampleId"].ToString();
            int samplingQty = Convert.ToInt32(_data["samplingQty"].ToString());

            var isOk = await _repository.Context.Updateable<QmsBusiIpqcinspectionitemEntity>().SetColumns(it => new QmsBusiIpqcinspectionitemEntity()
            {
                SamplingQty = samplingQty,
                ReceivedQty = samplingQty,
                LastModifyTime = DateTime.Now,
                LastModifyUserId = _userManager.UserId
            }).Where(x => x.Code == code && x.SampleId == sampleId).ExecuteCommandHasChangeAsync();
            if (!isOk)
                throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 批量删除检验项目数据.
        /// </summary>
        /// <param name="ids">主键数组.</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    // 开启事务
                    _db.BeginTran();

                    // 批量删除检验批项目结果
                    await _repository.Context.Updateable<QmsBusiIpqcinspectionitemdataEntity>().SetColumns(it => new QmsBusiIpqcinspectionitemdataEntity()
                    {
                        DeleteTime = DateTime.Now,
                        DeleteMark = 1,
                        DeleteUserId = _userManager.UserId
                    }).Where(it => ids.Contains(it.InspectionItem)).ExecuteCommandHasChangeAsync();

                    // 批量删除检验批项目缺陷记录
                    await _repository.Context.Updateable<QmsBusiIpqcinspectionitemdefectEntity>().SetColumns(it => new QmsBusiIpqcinspectionitemdefectEntity()
                    {
                        DeleteTime = DateTime.Now,
                        DeleteMark = 1,
                        DeleteUserId = _userManager.UserId
                    }).Where(it => ids.Contains(it.InspectionItem)).ExecuteCommandHasChangeAsync();

                    // 批量删除检验项目数据
                    await _repository.Context.Updateable<QmsBusiIpqcinspectionitemEntity>().SetColumns(it => new QmsBusiIpqcinspectionitemEntity()
                    {
                        DeleteTime = DateTime.Now,
                        DeleteMark = 1,
                        DeleteUserId = _userManager.UserId
                    }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                    // 关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    // 回滚事务
                    _db.RollbackTran();

                    throw Oops.Oh(ErrorCode.COM1002);
                }
            }
        }

        /// <summary>
        /// 保存检验项目数据（APP）.
        /// </summary>
        /// <param name="data">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Submit([FromBody] JObject _data)
        {
            string code = _data["code"].ToString();
            if (!(await Save(code, _data)))
                throw Oops.Oh("保存检验项目数据异常");
        }

        /// <summary>
        /// 保存检验项目数据.
        /// </summary>
        /// <param name="code">检验批号.</param>
        /// <param name="_data">数据集.</param>
        /// <returns></returns>
        [NonAction]
        public async Task<bool> Save(string code, JObject _data)
        {
            try
            {
                var data = JArray.Parse(_data["dataArray"].ToString());
                var column = JArray.Parse(_data["columnArray"].ToString());
                List<QmsBusiIpqcinspectionitemEntity> ipqcInspectionitemEntityList = new List<QmsBusiIpqcinspectionitemEntity>();
                List<QmsBusiIpqcinspectionitemdataEntity> ipqcInspectionitemdataEntityList = new List<QmsBusiIpqcinspectionitemdataEntity>();
                foreach (var item in data)
                {
                    var ipqcInspectionitemEntity = new QmsBusiIpqcinspectionitemEntity();
                    ipqcInspectionitemEntity.Id = item["Id"].ToString();
                    ipqcInspectionitemEntity.Status = "NG";
                    ipqcInspectionitemEntity.Type = item["Type"].ToString();
                    ipqcInspectionitemEntity.Parameter = item["Parameter"].ToString();
                    ipqcInspectionitemEntity.Remarks = item["Remarks"].ToString();
                    ipqcInspectionitemEntity.DestructivenessQty = Convert.ToInt32(item["DestructivenessQty"].ToString());
                    ipqcInspectionitemEntity.ReceivedQty = Convert.ToInt32(item["ReceivedQty"].ToString());
                    ipqcInspectionitemEntity.RejectionQty = Convert.ToInt32(item["RejectionQty"].ToString());
                    int okCount = 0;
                    int ngCount = 0;
                    foreach (var col in column)
                    {
                        string index = col["index"].ToString();
                        string columnName = col["columnName"].ToString();

                        if (item["column" + index] != null)
                        {
                            var ipqcInspectionitemdataEntity = new QmsBusiIpqcinspectionitemdataEntity();
                            ipqcInspectionitemdataEntity.Code = code;
                            ipqcInspectionitemdataEntity.InspectionItem = ipqcInspectionitemEntity.Id;
                            ipqcInspectionitemdataEntity.Type = ipqcInspectionitemEntity.Type;
                            ipqcInspectionitemdataEntity.Number = Convert.ToInt32(index);
                            ipqcInspectionitemdataEntity.Serial = index.Equals(columnName) ? "" : columnName;
                            var jObject = JObject.Parse(item["column" + index].ToString());
                            ipqcInspectionitemdataEntity.Value = jObject["value"].ToString();
                            // 如果是定性，则查询是否有缺陷记录，有则标识为NG
                            if (ipqcInspectionitemdataEntity.Type.Equals("qualitative"))
                            {
                                ipqcInspectionitemdataEntity.Status = "OK";
                                if (await _repository.Context.Queryable<QmsBusiIpqcinspectionitemdefectEntity>()
                                .Where(x => x.InspectionItem == ipqcInspectionitemEntity.Id && x.Number == ipqcInspectionitemdataEntity.Number && x.DeleteMark == null && x.EnabledMark == 1).CountAsync() > 0)
                                {
                                    ipqcInspectionitemdataEntity.Status = "NG";
                                }
                            }
                            else
                            {
                                ipqcInspectionitemdataEntity.Status = jObject["status"].ToString();
                            }
                            // 检验项目OK NG计数
                            if (ipqcInspectionitemdataEntity.Status.Equals("OK")|| ipqcInspectionitemdataEntity.Status.Equals("UP") || ipqcInspectionitemdataEntity.Status.Equals("Down"))
                            {
                                okCount++;
                            }
                            else
                            {
                                ngCount++;
                            }
                            ipqcInspectionitemdataEntityList.Add(ipqcInspectionitemdataEntity);
                        }
                    }
                    //根据设定的接收数量和拒收数量判断检验项目OK NG
                    if (ipqcInspectionitemEntity.RejectionQty!=0 && ipqcInspectionitemEntity.RejectionQty <= ngCount)
                    {
                        ipqcInspectionitemEntity.Status = "NG";
                    }
                    else if (ipqcInspectionitemEntity.ReceivedQty <= okCount)
                    {
                        ipqcInspectionitemEntity.Status = "OK";
                    }
                    else
                    {
                        ipqcInspectionitemEntity.Status = "NG";
                    }
                    ipqcInspectionitemEntityList.Add(ipqcInspectionitemEntity);

                }

                _db.BeginTran();
                // 保存检验批项目信息
                var isOk = await _repository.Context.Updateable(ipqcInspectionitemEntityList).UpdateColumns(x => new { x.Status, x.Parameter, x.Remarks, x.DestructivenessQty, x.LastModifyUserId, x.LastModifyTime }).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
                if (!isOk)
                    throw Oops.Oh(ErrorCode.COM1001);

                // 删除检验批项目检验数据
                await _repository.Context.Deleteable<QmsBusiIpqcinspectionitemdataEntity>().Where(x => x.Code == code).ExecuteCommandAsync();

                // 新增保存检验批项目检验数据
                var isOkI = await _repository.Context.Insertable(ipqcInspectionitemdataEntityList).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOkI < 1)
                    throw Oops.Oh(ErrorCode.COM1000);

                _db.CommitTran();
                return true;

            }
            catch (Exception ex)
            {
                _db.RollbackTran();
                return false;
            }
        }

        /// <summary>
        /// 新增检验项目.
        /// </summary>
        /// <param name="data">参数.</param>
        /// <returns></returns>
        [HttpPost("addItem")]
        public async Task AddItem([FromBody] JObject _data)
        {
            string code = _data["code"].ToString();
            string sampleId = _data["sampleId"].ToString();
            var productionQty = Convert.ToInt32(_data["productionQty"].ToString());
            int samplingQty = Convert.ToInt32(_data["samplingQty"].ToString());
            int receivedQty = Convert.ToInt32(_data["receivedQty"].ToString());
            int rejectionQty = Convert.ToInt32(_data["rejectionQty"].ToString());
            string samplingType = _data["samplingType"].ToString();
            string gLevel = _data["gLevel"].ToString();
            string gStringency = _data["gStringency"].ToString();
            string gQualityLimit = _data["gQualityLimit"].ToString();
            string fixedSamplingQty = _data["fixedSamplingQty"].ToString();
            string fixedRatio = _data["fixedRatio"].ToString();
            string aQL = _data["aQL"].ToString();
            var detailData = JArray.Parse(_data["detailData"].ToString());

            //获取抽样方案字典项
            var sampleTypeList = await _dictionaryDataService.GetList("sampleType");
            string samplingTypeDes = sampleTypeList.Find(x => x.EnCode == samplingType)?.FullName;

            // 如果抽样方案id为空则需要根据抽样方案类型来获取抽样数量，接收数量，拒收数量
            if (string.IsNullOrEmpty(sampleId))
            {
                // 1 国标AQL
                // 2 固定抽样
                // 3 固定比例
                // 4 自定义AQL
                // 5 执行时自行设置
                if (samplingType.Equals("1"))
                {
                    var nationalstandard = await _repository.Context.Queryable<QmsBaseNationalstandardEntity>()
                                     .Where(x => x.InspectionLevel == gLevel && x.Stage == gStringency && x.QualityLimit == gQualityLimit && x.LowerLimit <= productionQty && x.UpperLimit >= productionQty && x.DeleteMark == null && x.EnabledMark == 1).FirstAsync();
                    if (nationalstandard == null)
                        throw Oops.Oh("未匹配到国标抽样方案");
                    // 全检则抽样数量等于来料数量
                    if (nationalstandard.AllInspection.Equals("Y"))
                    {
                        samplingQty = productionQty;
                        receivedQty = samplingQty;
                    }
                    else
                    {
                        samplingQty = nationalstandard.SampleQty ?? 0;
                        receivedQty = nationalstandard.ReceivedQty ?? 0;
                    }
                    rejectionQty = 0;
                }
                else if (samplingType.Equals("2"))
                {
                    samplingQty = Convert.ToInt32(fixedSamplingQty);
                    receivedQty = samplingQty;
                    rejectionQty = 1;
                }
                else if (samplingType.Equals("3"))
                {
                    samplingQty = (int)Math.Ceiling(productionQty * (decimal.Parse(fixedRatio) / 100));//向上取整
                    receivedQty = samplingQty;
                    rejectionQty = 1;
                }
                else if (samplingType.Equals("4"))
                {
                    var samplingplandetail = await _repository.Context.Queryable<QmsBaseSamplingplanEntity, QmsBaseSamplingplandetailEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.Id == b.MainId))
                        .Where((a, b) => a.Id == aQL && b.LowerLimit <= productionQty && b.UpperLimit >= productionQty && a.DeleteMark == null && a.EnabledMark == 1 && b.DeleteMark == null && b.EnabledMark == 1).Select((a, b) => b).FirstAsync();
                    if (samplingplandetail == null)
                        throw Oops.Oh("未匹配到自定义AQL抽样方案");

                    samplingQty = samplingplandetail.SampleQty ?? 0;
                    receivedQty = samplingplandetail.ReceivedQty ?? 0;
                    rejectionQty = samplingplandetail.RejectionQty ?? 0;

                }
                else if (samplingType.Equals("5"))
                {
                    samplingQty = Convert.ToInt32(fixedSamplingQty);
                    receivedQty = samplingQty;
                    rejectionQty = 1;
                }
            }
            else
            {
                var ipqcInspectionitemInfo = await _repository.Context.Queryable<QmsBusiIpqcinspectionitemEntity>().Where(x => x.Code == code && x.SampleId == sampleId && x.DeleteMark == null).FirstAsync();
                samplingType = ipqcInspectionitemInfo.SamplingType;
                samplingTypeDes = ipqcInspectionitemInfo.SamplingTypeDes;
                samplingQty = ipqcInspectionitemInfo.SamplingQty ?? 0;
                receivedQty = ipqcInspectionitemInfo.ReceivedQty ?? 0;
                rejectionQty = ipqcInspectionitemInfo.RejectionQty ?? 0;
            }

            if (samplingQty > productionQty)
                throw Oops.Oh("计数抽样数量结果：抽样数量大于生产数量，请检查");


            List<QmsBusiIpqcinspectionitemEntity> ipqcInspectionitemList = new List<QmsBusiIpqcinspectionitemEntity>();
            if (string.IsNullOrEmpty(sampleId))
            {
                sampleId = YitIdHelper.NextId().ToString();
            }
            int index = 1;
            foreach (var item in detailData)
            {
                string innspectionCode = item["innspectionCode"].ToString();
                string innspectionEntry = item["innspectionEntry"].ToString();
                string innspectionMethod = item["innspectionMethod"].ToString();
                string type = item["type"].ToString();
                string quantitativeStandards = item["quantitativeStandards"].ToString();
                var standardValue = decimal.Parse(item["standardValue"].ToString());
                var upperDeviation = decimal.Parse(item["upperDeviation"].ToString());
                var lowerDeviation = decimal.Parse(item["lowerDeviation"].ToString());
                var maximumValue = decimal.Parse(item["maximumValue"].ToString());
                var minimumValue = decimal.Parse(item["minimumValue"].ToString());
                var accuracy = Convert.ToInt32(item["accuracy"].ToString());
                string unit = item["unit"].ToString();
                string remarks = item["remarks"].ToString();
                string fileInfo = item["fileInfo"].ToString();
                string referTo = item["referTo"].ToString();
                string destructiveness = item["destructiveness"].ToString();

                QmsBusiIpqcinspectionitemEntity qmsBusiIpqcinspectionitemEntity = new QmsBusiIpqcinspectionitemEntity();
                qmsBusiIpqcinspectionitemEntity.Code = code;
                qmsBusiIpqcinspectionitemEntity.Status = "";
                qmsBusiIpqcinspectionitemEntity.Type = type;
                qmsBusiIpqcinspectionitemEntity.SampleId = sampleId;
                qmsBusiIpqcinspectionitemEntity.SamplingType = samplingType;
                qmsBusiIpqcinspectionitemEntity.SamplingTypeDes = samplingTypeDes;
                qmsBusiIpqcinspectionitemEntity.SamplingQty = samplingQty;
                qmsBusiIpqcinspectionitemEntity.InnspectionCode = innspectionCode;
                qmsBusiIpqcinspectionitemEntity.InnspectionEntry = innspectionEntry;
                qmsBusiIpqcinspectionitemEntity.InnspectionMethod = innspectionMethod;

                // 获取检验项目名称
                var innspectionitemsEntity = await _repository.Context.Queryable<QmsBaseInnspectionitemsEntity>().Where(x => x.Id == innspectionCode).FirstAsync();
                qmsBusiIpqcinspectionitemEntity.InnspectionName = innspectionitemsEntity.InnspectionName;

                // 获取检验条目名称
                var innspectionentryEntity = await _repository.Context.Queryable<QmsBaseInnspectionentryEntity>().Where(x => x.Id == innspectionEntry).FirstAsync();
                qmsBusiIpqcinspectionitemEntity.InnspectionEntryName = innspectionentryEntity.InnspectionName;

                // 获取检验方法名称
                var innspectionmethodEntity = await _repository.Context.Queryable<QmsBaseInnspectionmethodEntity>().Where(x => x.Id == innspectionMethod).FirstAsync();
                qmsBusiIpqcinspectionitemEntity.InnspectionMethodName = innspectionmethodEntity.Name;

                // 验证是否重复添加
                if (await _repository.Context.Queryable<QmsBusiIpqcinspectionitemEntity>()
               .Where(x => x.Code == code && x.SampleId == sampleId && x.InnspectionCode == innspectionCode && x.InnspectionEntry == innspectionEntry && x.DeleteMark == null && x.EnabledMark == 1).CountAsync() > 0)
                {
                    throw Oops.Oh("检验项目重复添加，请确认。检验项目：" + innspectionitemsEntity.InnspectionName + "；检验条目：" + innspectionentryEntity.InnspectionName);
                }

                qmsBusiIpqcinspectionitemEntity.QuantitativeStandards = quantitativeStandards;
                qmsBusiIpqcinspectionitemEntity.StandardValue = standardValue;
                qmsBusiIpqcinspectionitemEntity.UpperDeviation = upperDeviation;
                qmsBusiIpqcinspectionitemEntity.LowerDeviation = lowerDeviation;
                qmsBusiIpqcinspectionitemEntity.MaximumValue = maximumValue;
                qmsBusiIpqcinspectionitemEntity.MinimumValue = minimumValue;
                qmsBusiIpqcinspectionitemEntity.Unit = unit;
                qmsBusiIpqcinspectionitemEntity.Accuracy = accuracy;
                qmsBusiIpqcinspectionitemEntity.FileInfo = fileInfo;
                qmsBusiIpqcinspectionitemEntity.ReceivedQty = receivedQty;
                qmsBusiIpqcinspectionitemEntity.RejectionQty = rejectionQty;
                qmsBusiIpqcinspectionitemEntity.Remarks = remarks;
                qmsBusiIpqcinspectionitemEntity.ReferTo = referTo;
                qmsBusiIpqcinspectionitemEntity.Destructiveness = destructiveness;
                qmsBusiIpqcinspectionitemEntity.DestructivenessQty = 0;
                qmsBusiIpqcinspectionitemEntity.Sort = index;
                qmsBusiIpqcinspectionitemEntity.Volt = "";
                qmsBusiIpqcinspectionitemEntity.VType = "";
                qmsBusiIpqcinspectionitemEntity.Formula = "";
                qmsBusiIpqcinspectionitemEntity.Parameter = "[]";
                qmsBusiIpqcinspectionitemEntity.Exempt = "N";
                qmsBusiIpqcinspectionitemEntity.AutoFlag = "N";
                ipqcInspectionitemList.Add(qmsBusiIpqcinspectionitemEntity);
                index++;
            }

            // 新增检验项目
            var isOkI = await _repository.Context.Insertable(ipqcInspectionitemList).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            if (isOkI < 1)
                throw Oops.Oh(ErrorCode.COM1000);

        }
    }
}
